import React from 'react'
import PropTypes from 'prop-types'
import YearDropdownOptions from './year_dropdown_options'
import onClickOutside from 'react-onclickoutside'

var WrappedYearDropdownOptions = onClickOutside(YearDropdownOptions)

export default class YearDropdown extends React.Component {
  static propTypes = {
    dropdownMode: PropTypes.oneOf(['scroll', 'select']).isRequired,
    maxDate: PropTypes.object,
    minDate: PropTypes.object,
    onChange: PropTypes.func.isRequired,
    scrollableYearDropdown: PropTypes.bool,
    year: PropTypes.number.isRequired
  }

  state = {
    dropdownVisible: false
  }

  renderSelectOptions = () => {
    const minYear = this.props.minDate ? this.props.minDate.year() : 1900
    const maxYear = this.props.maxDate ? this.props.maxDate.year() : 2100

    const options = []
    for (let i = minYear; i <= maxYear; i++) {
      options.push(<option key={i} value={i}>{i}</option>)
    }
    return options
  }

  onSelectChange = (e) => {
    this.onChange(e.target.value)
  }

  renderSelectMode = () => (
    <select
        value={this.props.year}
        className="react-datepicker__year-select"
        onChange={this.onSelectChange}>
      {this.renderSelectOptions()}
    </select>
  )

  renderReadView = (visible) => (
    <div key="read" style={{visibility: visible ? 'visible' : 'hidden'}} className="react-datepicker__year-read-view" onClick={this.toggleDropdown}>
      <span className="react-datepicker__year-read-view--down-arrow" />
      <span className="react-datepicker__year-read-view--selected-year">{this.props.year}</span>
    </div>
  )

  renderDropdown = () => (
    <WrappedYearDropdownOptions
        key="dropdown"
        ref="options"
        year={this.props.year}
        onChange={this.onChange}
        onCancel={this.toggleDropdown}
        scrollableYearDropdown={this.props.scrollableYearDropdown} />
  )

  renderScrollMode = () => {
    const { dropdownVisible } = this.state
    let result = [this.renderReadView(!dropdownVisible)]
    if (dropdownVisible) {
      result.unshift(this.renderDropdown())
    }
    return result
  }

  onChange = (year) => {
    this.toggleDropdown()
    if (year === this.props.year) return
    this.props.onChange(year)
  }

  toggleDropdown = () => {
    this.setState({
      dropdownVisible: !this.state.dropdownVisible
    })
  }

  render () {
    let renderedDropdown
    switch (this.props.dropdownMode) {
      case 'scroll':
        renderedDropdown = this.renderScrollMode()
        break
      case 'select':
        renderedDropdown = this.renderSelectMode()
        break
    }

    return (
      <div
          className={`react-datepicker__year-dropdown-container react-datepicker__year-dropdown-container--${this.props.dropdownMode}`}>
        {renderedDropdown}
      </div>
    )
  }
}
